package com.company.fastsbapi.controller;

import com.company.fastsbapi.dataobject.model.student;
import com.company.fastsbapi.dataobject.ro.studentAddRO;
import com.company.fastsbapi.dataobject.ro.studentUpdateRO;
import com.company.fastsbapi.dataobject.vo.studentVO;
import com.company.fastsbapi.dataobject.vo.ResultVO;
import com.company.fastsbapi.service.studentService;
import com.company.fastsbapi.utils.ListBeanConvertUtil;
import com.company.fastsbapi.utils.ROValidUtil;
import com.company.fastsbapi.utils.ResultVOUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
* Created by CodeGenerator on 2020/09/08.
*/
@RestController
@RequestMapping("/student")
public class studentController {

    @Autowired
    private studentService studentService;

    @PostMapping
    public ResultVO add(@Valid @RequestBody studentAddRO studentAddRO, BindingResult result) {
        ROValidUtil.valid(result);
        studentService.addstudent(studentAddRO);
        return ResultVOUtil.returnSuccess();
    }

    @DeleteMapping("/{id}")
    public ResultVO delete(@PathVariable Integer id) {
    studentService.deletestudent(id);
    return ResultVOUtil.returnSuccess();
    }

    @PutMapping
    public ResultVO update(@RequestBody studentUpdateRO studentUpdateRO) {
        studentService.updatestudent(studentUpdateRO);
        return ResultVOUtil.returnSuccess();
    }

    @GetMapping("/{id}")
    public ResultVO detail(@PathVariable Integer id) {
        student student = studentService.findstudent(id);
        studentVO studentVO = new studentVO();
        BeanUtils.copyProperties(student, studentVO);
        return ResultVOUtil.returnSuccess("student", studentVO);
    }

    @GetMapping
    public ResultVO list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer size) {
        PageRequest pageRequest = new PageRequest(page, size);
        Page<student> studentPage = studentService.findstudentPage(pageRequest);
        List<student> studentList = studentPage.getContent();
        List<studentVO> studentVOList = ListBeanConvertUtil.convert(studentList, studentVO.class);
        return ResultVOUtil.returnSuccess("student_list", studentVOList);
    }

}